<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Websocket</title>
</head>
<body>
<h1>Echo Test</h1>

<input type="text" id="sendText">

<button id="sendBtn">发送</button>
<!-- 接收部分 -->
<div id="recv"></div>
<script>
     // 建立websocket链接
    var oBtn=document.getElementById("sendBtn");
    var oRecv=document.getElementById('recv');
    var sendText=document.getElementById('sendText')
	var websocket=new WebSocket("ws://localhost:888/");
	function ShowMessage(str){
	var div=document.createElement('div');
	    div.innerHTML=str;
	    document.body.appendChild(div)
	}
	// 建立链接后的回调函数
	websocket.onopen=function(){
		console.log('websocket onen');
		oBtn.onclick=function(){
			var txt=sendText.value;
			if(txt){
				websocket.send(txt);
			}
		}

		
	}
		// 在链接关闭时触发
	websocket.onclose=function(){
		console.log('websocket close');
	}
       // 接受消息时触发的回调函数
	websocket.onmessage=function(e){
        ShowMessage(e.data)
	}

</script>
	

</body>
</html>